import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { articleApi, categoryApi } from '../../api/knowledge';
import { Spin, Card, Typography, Breadcrumb, Button, message, Tag, Divider } from 'antd';
import { ArrowLeftOutlined, EyeOutlined, StarOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import './index.css';

const { Title, Text } = Typography;

const ArticleDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [article, setArticle] = useState(null);
  const [categoryOne, setCategoryOne] = useState(null);
  const [categoryTwo, setCategoryTwo] = useState(null);

  // 获取文章详情
  useEffect(() => {
    const fetchArticleDetail = async () => {
      setLoading(true);
      try {
        const articleData = await articleApi.getDetail(id);
        setArticle(articleData);
        
        // 获取分类信息
        if (articleData) {
          try {
            const categoryOneData = await categoryApi.getLevelOneDetail(articleData.categoryOneId);
            setCategoryOne(categoryOneData);
            
            const categoryTwoData = await categoryApi.getLevelTwoDetail(articleData.categoryTwoId);
            setCategoryTwo(categoryTwoData);
          } catch (error) {
            console.error('获取分类信息失败:', error);
          }
        }
      } catch (error) {
        message.error('获取文章详情失败：' + error.message);
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchArticleDetail();
    }
  }, [id]);

  // 处理使用按钮点击
  const handleUseClick = async () => {
    try {
      await articleApi.increaseUseCount(id);
      message.success('已记录使用');
      // 更新本地文章数据
      setArticle(prev => ({
        ...prev,
        useCount: (prev.useCount || 0) + 1
      }));
    } catch (error) {
      message.error('操作失败：' + error.message);
    }
  };

  // 返回首页列表
  const goBack = () => {
    navigate('/');
  };

  return (
    <div className="article-detail-container">
      <Spin spinning={loading}>
        {article && (
          <>
            <div className="article-detail-header">
              <Button 
                type="text" 
                icon={<ArrowLeftOutlined />} 
                onClick={goBack}
                className="back-button"
              >
                返回
              </Button>
              
              <Breadcrumb className="article-breadcrumb">
                <Breadcrumb.Item>知识库</Breadcrumb.Item>
                {categoryOne && <Breadcrumb.Item>{categoryOne.name}</Breadcrumb.Item>}
                {categoryTwo && <Breadcrumb.Item>{categoryTwo.name}</Breadcrumb.Item>}
                <Breadcrumb.Item>{article.title}</Breadcrumb.Item>
              </Breadcrumb>
              
              <Button 
                type="primary" 
                onClick={handleUseClick}
                className="use-button"
              >
                记录使用
              </Button>
            </div>
            
            <Card className="article-detail-card">
              <div className="article-title-section">
                <Title level={2}>{article.title}</Title>
                <div className="article-meta">
                  <Tag icon={<EyeOutlined />} color="blue">浏览: {article.viewCount}</Tag>
                  <Tag icon={<StarOutlined />} color="green">使用: {article.useCount}</Tag>
                  <Text type="secondary">
                    创建时间: {new Date(article.createdAt).toLocaleString()}
                  </Text>
                </div>
              </div>
              
              {article.summary && (
                <div className="article-summary">
                  <Text strong>摘要：</Text>
                  <Text>{article.summary}</Text>
                </div>
              )}
              
              <Divider />
              
              <div className="article-content">
                <ReactMarkdown>{article.content}</ReactMarkdown>
              </div>
            </Card>
          </>
        )}
      </Spin>
    </div>
  );
};

export default ArticleDetail;
